<?php
class CheckoutHelper extends CComponent {
    public static function getCartInfo() {
        if (isset(Yii::app()->session['quoteid'])) {
            $cart = Quote::model()->findByPk(Yii::app()->session['quoteid']);
        }
        if(!isset($cart)){
            $cart = new Quote('');
            $cart->created_at = date('Y-m-d H:i:s');
            $cart->updated_at = date('Y-m-d H:i:s');
            $cart->is_active = 1;
            
            if($cart->save()){
                // Lưu cart_id vào session
                Yii::app()->session['quoteid'] = $cart->quote_id;
//                echo 'Yii::app()->session[quoteid] after save: '.Yii::app()->session['quoteid'].'<br />';
//            }else{
//                echo 'Lỗi';
            }
            
        }
        return $cart;
    }
    
    public static function updateCart($cart,$products=array()){
        $cart->items_count = 0;
        $cart->items_qty = 0;
        $cart->subtotal = 0;
        $cartItems = QuoteItem::model()->findAll('quote_id = :quote_id',array(':quote_id'=>$cart->quote_id));
        $existedProducts = array();
        $productIds = array_keys($products);
        foreach($cartItems as $item){
            if(in_array($item->product_id, $productIds)){ // Sản phẩm đã có trong giỏ hàng
                // Thêm item->product_id vào mảng các sản phẩm đã tồn tại trong giỏ hàng
                $existedProducts[] = $item->product_id;
                // Tăng số lượng (hiện hệ thống chỉ cho phép add 1 sản phẩm vào giỏ hàng)
                $item->qty = $item->qty + $products[$item->product_id];
                $item->row_total=$item->qty*$item->price;
                $item->updated_at = date('Y-m-d H:i:s');
                $item->status = 1;
                // Cập nhật số lượng mới
                $item->save();
            }
            $cart->items_count++;
            $cart->items_qty += $item->qty;
            $cart->subtotal += $item->row_total;
        }
        
        // Kiểm tra xem có item nào chưa được add vào giỏ hàng hay không
        $newItems = array_diff($productIds,$existedProducts);
        
        if(count($newItems)){ // Nếu có item mới => thêm row vào giỏ hàng
            foreach($newItems as $prdtId){
                $product = Product::model()->findByPk($prdtId);
                if($product){
                    $newQuoteItem = new QuoteItem();
                    $newQuoteItem->item_id = null;
                    $newQuoteItem->product_id = $prdtId;
                    $newQuoteItem->qty = $products[$prdtId];
                    $cart->items_qty += $newQuoteItem->qty;
                    //set special price
                    $newQuoteItem->price = $product->price;
                    $newQuoteItem->item_id = null;
                    $newQuoteItem->row_total=$newQuoteItem->qty*$newQuoteItem->price;
                    $cart->subtotal += $newQuoteItem->row_total;
                    $newQuoteItem->quote_id = $cart->quote_id;
                    $newQuoteItem->created_at = date('Y-m-d H:i:s');
                    $newQuoteItem->updated_at = date('Y-m-d H:i:s');
                    $newQuoteItem->status = 1;
                    $newQuoteItem->save();
                }
            }
        }
        
        // Cập nhật tổng số sản phẩm, tổng số lượng sản phẩm, tổng tiền của giỏ hàng
        //Yii::app()->session['numberItemCart'] = $cart->items_qty;
        Yii::app()->session['numberItemCart'] = count($cartItems)+count($newItems);
        $cart->grand_total = $cart->subtotal;
        $cart->updated_at = date('Y-m-d H:i:s');
        $cart->save();
    }
    
    public static function placeOrder($customer,$quote,$payment,&$result,$site=null,$params=array()){
        $order = new Order();
        $customer->scenario='checkout';
        if ($customer->verify($result)) {
            $order->customer = $customer;
            // Kiểm tra thông tin giỏ hàng
            if ($quote->verify($result)) {
                $order->quote = $quote;

                // Kiểm tra phương thức thanh toán				
                if ($payment->verify($result)) {
                    $order->payment = $payment;
                    $order->comment=isset($params['comment'])?$params['comment']:'';
                    $order->company_code = Yii::app()->params['company_code'];
                    //set buy method of customer                                     
                    $order->buy_method = (isset($params['buy_method']) && $site) ? $params['buy_method'] : (Order::BUY_METHOD_WEBSITE);
                    $order->transport_method = (isset($params['payment']['transport_m'])) ? $params['payment']['transport_m'] : 2;	                                        
                    $order->coupon_code=isset($params['payment']['coupon_code'])? trim(strtoupper($params['payment']['coupon_code'])):'';                   
                    $result = $order->place(null);
                    //Đặt hàng thành công thì gửi mail hướng dẫn khách hàng
                    if($result['type'] == 'success'){
                        SystemHelper::helper()->emailSendOrderPlaceSuccess($order);
//                        if(is_null($site)){
//                                // insert dữ liệu vảo bảng chi tiết shiphangf
//                                $model = new VgshippingDetail();
//                                $model->saveShippingDetail($quote->entity_id, $customer, $result['order_id']);
//                        }
                    }
                    return true;
                } else {
                    $result['type'] = 'error';
                    $result['message'] = 'Hiện tại không có phương thức thanh toán nào phù hợp';
                    return false;
                }
            }
        } else {
            return false;
        }
    }
	
	public static function getShippingAmountVendor($quoteItems, $district_id = null){
		$ary_vendor = array();
		if(!empty($quoteItems)){
			foreach($quoteItems as $key => $value){
				if(isset($ary_vendor[$value['vendor_code']])){
					$ary_vendor[$value['vendor_code']]['attributes'][] = $value->attributes;
					if(!isset($ary_vendor[$value['vendor_code']]['total_price'])){
						$ary_vendor[$value['vendor_code']]['total_price'] = $value->price;
					} else{
						$ary_vendor[$value['vendor_code']]['total_price'] += $value->price;
					}
				} else{
					$ary_vendor[$value['vendor_code']]['attributes'][] = $value->attributes;
					if(!isset($ary_vendor[$value['vendor_code']]['total_price'])){
						$ary_vendor[$value['vendor_code']]['total_price'] = $value->price;
					} else{
						$ary_vendor[$value['vendor_code']]['total_price'] += $value->price;
					}
				}
			}
		}
		if(is_null($district_id)){			
			$customer_id = Yii::app()->customerUser->id;
			$customer_addresses = CustomerAddress::model()->find('customer_id=:customer_id', array(':customer_id' => $customer_id));
			if($customer_addresses){
				$customer_district = $customer_addresses->district_id;
			}else{
				$customer_district = 0;
			}		
		}else{		
			$customer_district = $district_id;
		}
		$model_ship = new Vgshipping();
		foreach($ary_vendor as $vendor => $item){
			$ary_vendor[$vendor]['ship'] = $model_ship->getPriceShippingVendor($customer_district, $vendor, $item['total_price']);
		}
		$ary_vendor['total_ship'] = 0;
		foreach($ary_vendor as $key => $value){
			if(!isset($ary_vendor['total_ship'])){
				$ary_vendor['total_ship'] = $value['ship'];
			} else{
				$ary_vendor['total_ship'] += $value['ship'];
			}
			
		}
		return $ary_vendor;
	}
        
	public static function getListCart($cusId){
		$cart = Quote::model()->find('customer_id=:customer_id AND COALESCE(reserved_order_id,0)=0',array(':customer_id'=>$cusId));
		if($cart){
			$lstQuoteItem = Yii::app()->db->createCommand()
			->select('item_id,product_id,name,qty,price,row_total')
			->from('ncs_sales_flat_quote_item')
			->where('quote_id=:quote_id',array(':quote_id'=>$cart->entity_id))
			->order('item_id DESC')
			->limit('2')
			->queryAll();
			return $lstQuoteItem;
		}
		return null;
	}
	public static function getListCartGuest($quoteId){
		$lstQuoteItem = Yii::app()->db->createCommand()
		->select('item_id,product_id,name,qty,price,row_total')
		->from('ncs_sales_flat_quote_item')
		->where('status=1 AND quote_id=:quote_id',array(':quote_id'=>$quoteId))
		->order('item_id DESC')
		->limit('2')
		->queryAll();
		return $lstQuoteItem;
	}
        public static function getCountItemGuest($quoteId){
            $count = 0;
            $lstQuoteItem = Yii::app()->db->createCommand()
		->select('item_id,product_id,name,qty,price,row_total')
		->from('ncs_sales_flat_quote_item')
		->where('status=1 AND quote_id=:quote_id',array(':quote_id'=>$quoteId))
		->queryAll();
                $count = count($lstQuoteItem);
            return $count;
        }
        
        public static function getCountItemCustomer($cusId){
            $count = 0;
            $cart = Quote::model()->find('customer_id=:customer_id AND COALESCE(reserved_order_id,0)=0',array(':customer_id'=>$cusId));
            if($cart){
                    $lstQuoteItem = Yii::app()->db->createCommand()
                    ->select('item_id,product_id,name,qty,price,row_total')
                    ->from('ncs_sales_flat_quote_item')
                    ->where('status=1 AND quote_id=:quote_id',array(':quote_id'=>$cart->entity_id))
                    ->queryAll();
                    $count = count($lstQuoteItem);
            }
            return $count;
        }
            
        public static function getMessageSuccess($order){
		$result = array();
		$constantCheckout = ConstantHelper::checkout();
		$result['title'] = $constantCheckout['title_complete'][0];
		$result['message'] = $constantCheckout['message_complete'][0];
		if($order){
			$result['title'] = ($order->order_status == Order::ORDER_STATUS_PAID)? $constantCheckout['title_complete'][1] : $constantCheckout['title_complete'][0];		
			if($order->transport_method == 2){
				//mua tai quay				
				$result['message'] = ($order->order_status == Order::ORDER_STATUS_PAID)? $constantCheckout['message_complete'][1] : $constantCheckout['message_complete'][2];				
			}else{
				$orderAddress = OrderAddress::model()->find('parent_id=:parent_id',array(':parent_id'=>$order->id));	
				if($orderAddress){
					if(in_array($orderAddress->region_id,ConstantHelper::region('internal'))){
						$result['message'] = ($order->order_status == Order::ORDER_STATUS_PAID)? $constantCheckout['message_complete'][3] : $constantCheckout['message_complete'][4];
					}else{
						$result['message'] = ($order->order_status == Order::ORDER_STATUS_PAID)? $constantCheckout['message_complete'][5] : $constantCheckout['message_complete'][6];						
					}
				}			
			}
		}
		
		return $result;		
	}
}
?>
